package com.link.base.base.annualplan.service;

import com.link.base.base.annualplan.dao.mybatis.mapper.AnnualPlanMapper;
import com.link.base.base.annualplan.model.AnnualPlan;
import com.link.base.base.system.model.Period;
import com.link.base.base.system.service.PeriodService;
import com.link.base.base.workbreakdown.model.WorkBreakdown;
import com.link.base.base.workbreakdown.service.WorkBreakdownService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liushoulong
 * @date 2018-11-06
 * @desc 年度规划Service
 */
@Service
public class AnnualPlanServiceImpl extends BasicServiceImpl<AnnualPlan> implements AnnualPlanService {

    @Resource
    private AnnualPlanMapper annualPlanMapper;

    @Resource
    private PeriodService periodService;

    @Resource
    private WorkBreakdownService workBreakdownService;

    @Override
    public BasicMapper<AnnualPlan> getBasicMapper() {
        return annualPlanMapper;
    }


    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void annualPlanInsert(AnnualPlan annualPlan) throws Exception {
        String currentYear = annualPlan.getPartYear();
        if (StringUtils.isBlank(currentYear)) {
            throw new ServiceException("ANNUAL-001");
        }
        Period period = new Period();
        period.setType("Month");
        period.setPartYear(currentYear);
        period.setPageFlag(false);
        List<Period> periodList = periodService.queryByExamplePage(period);
        if (periodList.size() <= 0) {
            throw new ServiceException("ANNUAL-002");
        }
        /*新建年度规划记录*/
        Long objectId = keyGenerateService.keyGenerate();
        /*新建任务分解*/
        for (Period p : periodList) {
            WorkBreakdown workBreakdown = new WorkBreakdown();
            workBreakdown.setAnnualPlanId(objectId);
            workBreakdown.setPeriodId(p.getId());
            workBreakdown.setTaskVolume(0.00);
            workBreakdownService.insert(workBreakdown);
        }
        annualPlan.setId(objectId);
        insert(annualPlan);
    }

    /**
     * 级联删除年度计划 和 分解任务
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void deleteCascadePlan(AnnualPlan entity) throws Exception {
        if (null == entity.getId()) {
            throw new ServiceException("PUBLIC-007");
        }
        WorkBreakdown workBreakdown = new WorkBreakdown();
        workBreakdown.setAnnualPlanId(entity.getId());
        workBreakdownService.deleteByAnnualPlanId(workBreakdown);
        deleteById(entity);
    }
}
